import { mapState } from 'vuex'
import { share } from '@/utils/common-api.js'
import { create, draw } from '@/utils/posterCreated.js'
import iSharePopup from '@/components/i-share-popup.vue'
import { pathToBase64, base64ToPath } from '@/utils/image-tools/index.js'
import { icon, qrcode } from '@/static/img/images/iconPoster.js' // 标题上的星星图标

export default {
  components: { iSharePopup },
  onReady() {
    this.ctx = uni.createCanvasContext('ctx', this)
  },
  data() {
    return {
      iconxing: icon, // 小星星图
      posterValData: null, // 当前选中的海报数据
      bgimglist: [], // 预选背景图列表
      // 填充海报的数据
      posterData: {
        bigTitle: '大标题最多七字',
        smallTitle: '副标题最多不能超过十二字',
        goods: [
          {
            img: '',
            carBrand: '奥迪',
            carType: '2020款巴拉巴拉巴拉巴拉巴拉巴拉巴拉巴拉',
            guidePrice: '52.36万/下23.22万',
            actualPrice: 26.38,
          },
        ],
        store: {
          qrcode: qrcode,
          storeName: '四川荣威4s店',
          headerImg: qrcode,
        },
        bgImg: '',
      },
      loadingBgFlag: false, // 加载背景图列表

      sharePopupShow: false, // 分享弹窗

      ctx: null,
      ctxData: null, // 画布生成需要的数据
      topImg: '',
      storeName: '',
      companyName: ''
    }
  },

  computed: {
    // vuex里海报选中的商品
    ...mapState({
      selectedGoodsData: state => state.poster.selectedGoodsData, // 选择的商品
      posterType: state => state.poster.posterType, // 海报类型
      posterBgTemplate: state => state.poster.posterBgTemplate, // 海报模板
      // storeName: state => state.userInfoDetail.store.storeName,
      headImg: state => state.userInfoDetail.user.headImg,
    }),
  },

  onLoad(op){
    console.log(op)
    this.topImg = op.topImg
    this.storeName = op.storeName
    this.companyName = op.companyName
  },

  created() {
    this.init()
    this.getBgImgs()
  },

  methods: {
    init() {
      this.posterValData = { ...this.posterBgTemplate }

      // 赋值给大小标题
      this.posterData.bigTitle = this.posterValData.bigTitle
      this.posterData.smallTitle = this.posterValData.smallTitle
      this.posterData.store.storeName = this.storeName
      this.posterData.store.headerImg = this.topImg || 'https://files.yzsheng.com/client/store/store_default.png'

      // 将store选择的商品赋值给当前页goods变量
      this.posterData.goods = this.selectedGoodsData.map(item => ({
        img: item.goodImg,
        carBrand: item.car_Type_Name,
        carType: item.configuration_Name,
        guidePrice: item.factory_Price,
        actualPrice: item.bus_Price,
      }))
    },

    //获取背景图
    async getBgImgs() {
      try {
        this.loadingBgFlag = true
        const { data } = await this.$api.jsonData.getPosters()
        // 根据海报类型获取对应的海报图片列表，type海报类型是上一个页面传入的数据
        this.bgimglist = data[this.posterValData.type]
        this.loadingBgFlag = false
      } catch (err) {
        //
        this.loadingBgFlag = false
      }
    },

    // 切换选择海报
    selectBgPoster(itemData) {
      this.posterValData = itemData
    },
    //返回
    goback() {
      uni.navigateBack({
        delta: 1,
      })
    },

    // 清空标题值
    resetVal(str) {
      this.posterData[str] = ''
    },

    // 去分享
    goShare() {
      this.sharePopupShow = true

      // 处理商品数据，在回调中执行画布逻辑
      this.handleGoodsData(() => {
        // 创建画布上的海报图
        draw({
          type: 'multipleGoods',
          canvas: this.ctx,
          data: this.ctxData,
        })
      })
    },

    // 处理生成海报的商品数据
    handleGoodsData(callback) {
      this.ctxData = JSON.parse(JSON.stringify(this.posterData))
      this.ctxData.color = this.posterValData.color
      this.posterData.bgImg = this.posterValData.url

      let imgPaths = [] // 异步处理图片，同步获取处理结果

      // 处理商品图
      this.posterData.goods.forEach(g => {
        imgPaths.push(
          new Promise((resolve, reject) => {
            // 将图片网络路径下载转换图片临时路径
            uni.downloadFile({
              url: g.img,
              success: res => {
                resolve(res)
              },
            })
          })
        )
      })
      Promise.all(imgPaths).then(result => {
        Promise.all(result.map(p => pathToBase64(p.tempFilePath))).then(
          resImg => {
            this.ctxData.goods.forEach((g, i) => {
              g.img = resImg[i]
            })

            // 下载图片promise
            let dlPms = []
            // 需要下载的图片
            let dlImgs = [
              this.posterData.bgImg,
              this.posterData.store.headerImg,
            ]

            dlImgs.forEach(img => {
              dlPms.push(
                new Promise((resolve, reject) => {
                  // 下载背景,头像图
                  uni.downloadFile({
                    url: img,
                    success: res => {
                      resolve(res)
                    },
                  })
                })
              )
            })

            Promise.all(dlPms).then(resDlImg => {
              Promise.all(
                resDlImg.map(p => pathToBase64(p.tempFilePath))
              ).then(imgimg => {
                this.ctxData.bgImg = imgimg[0]
                this.ctxData.store.headerImg = imgimg[1]
                callback('ok')
              })
            })
          }
        )
      })
    },

    /*
     * 创建生成画布上的海报图
     * 且将生成的海报图片路径转成本地图片路径
     */
    createdPoster(callback) {
      create('ctx', res => {
        uni.getImageInfo({
          src: res.tempFilePath,
          success: resFile => {
            // 上传生成的本地图片
            this.$api.files
              .uploadImg({
                filePath: resFile.path,
              })
              .then(resImg => {
                console.log('看看图片', resImg)
                callback(resImg) // 回调操作
              })
              .catch(err => {
                console.log('no:', err)
              })
          },
        })
      })
    },

    // 调用分享或下载操作
    handleShare(type) {
      uni.showLoading({
        title: '正在生成海报...',
      })

      setTimeout(() => {
        // 下载
        if (type === 'download') {
          // 下载到本地不用上传图片
          create('ctx', res => {
            uni.hideLoading() // 关闭生成中提示
            // #ifndef H5
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                this.sharePopupShow = false
                uni.showToast({
                  title: '已保存到本地相册',
                  duration: 2000,
                })
              },
            })
            // #endif
          })
        } else {
          // 调用生成海报方法
          this.createdPoster(({ baseUrl, url }) => {
            let imgUrl = baseUrl + url // 图片地址
            uni.hideLoading() // 关闭生成中提示
            // 分享方法
            share(
              {
                type: 2,
                imageUrl: imgUrl,
                scene: type,
              },
              status => {
                if (status) {
                  this.sharePopupShow = false
                  uni.hideLoading() // 关闭生成中提示
                } else {
                  uni.showToast({
                    title: '分享失败',
                    duration: 2000,
                  })
                }
              }
            )
          })
        }
      }, 2000)
    },
  },
}
